<template>
    <el-dialog :close-on-click-modal="false" :title="titleMap[mode]" v-model="visible" :width="980" destroy-on-close @closed="$emit('closed')">
        <div class="tipsbox">
            <div class="tips-title">请根据序号依次录入!!! </div>
            <div class="tips-con">
                课程名称选项中的数字说明：
                <span style="color: green;">九宫格绿色格子单词数量 / 词库单词数量</span>
                （例如：100/2506，100代表绿色格子有100个单词，2506代表该词库共有2506个单词）
            </div>
        </div>
        <el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="100px" label-position="right" v-loading="loading">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="机构名称" prop="">
                        {{ agentName }}
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="①课程类型" prop="courseType">
                        <el-select v-model="form.courseType" placeholder="请选择课程类型" clearable filterable style="width: 100%;" @change="selectCourseTypeFun">
                            <el-option label="30分钟课" :value="1"></el-option>
                            <el-option label="60分钟课" :value="2"></el-option>
                            <el-option label="体验课" :value="4"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="②交付方式" prop="listenType">
                        <el-select v-model="form.listenType" placeholder="请选择交付方式" clearable filterable style="width: 100%;">
                            <el-option label="线上" :value="1"></el-option>
                            <el-option label="机构" :value="2"></el-option>
                            <el-option label="上门" :value="3"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="③学员姓名" prop="userId">
                        <el-select
                            style="width: 100%;"
                            v-model="form.userId"
                            filterable
                            remote
                            clearable
                            placeholder="请输入学员姓名搜索"
                            :disabled="form.id ? true : false"
                            :remote-method="searchUserHander"
                            @change="selectUserFun"
                            :loadings="userLoading">
                                <el-option
                                    v-for="item in userList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                    :disabled="item.disabled">
                                    <span style="float: left">{{ item.name }}</span>
                                    <span style="float: right; color: #8492a6;" v-if="form.courseType == 1">{{ item.classHour30 }}</span>
                                    <span style="float: right; color: #8492a6;" v-if="form.courseType == 2">{{ item.classHour60 }}</span>
                                    <span style="float: right; color: #8492a6;" v-if="form.courseType == 3">{{ item.classHour120 }}</span>
                                </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="④课程名称" prop="courseId" v-if="form.courseType == 4">
                        <el-select v-model="form.courseId" placeholder="请选择" clearable filterable style="width: 100%;">
                            <el-option :label=" item.course ? item.course.name : item.name" :value="item.course ? item.course.id : item.id" v-for="item in userCourses">
                                <span style="float: left;">{{ item.course ? item.course.name : item.name }}</span>
                                <span style="float: right; color: red;" v-if="item.course">{{ item.course.learnNum + '/' + item.course.words }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="④课程名称" prop="courseId" v-if="form.courseType != 4">
                        <el-button type="primary" @click="addCourseFun" size="small">选择课程</el-button>
                        <el-button type="text" v-if="selectedCourses && selectedCourses.length">已选择{{selectedCourses.length}}个课程</el-button>
			        </el-form-item>
                </el-col>    
                <el-col :span="8">
                    <el-form-item label="⑤预约次数" prop="number" v-if="!form.id">
                        <el-select v-model="form.number" placeholder="请选择" clearable filterable style="width: 100%;">
                            <el-option :label="item" :value="item" v-for="item in appointmentNumbers"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>    
                <el-col :span="8">
                    <el-form-item label="⑥间隔时间" prop="type" v-if="!form.id">
                        <el-select v-model="form.type" placeholder="请选择" clearable filterable style="width: 100%;">
                            <el-option label="同一天（间隔0分钟）" :value="1"></el-option>
                            <el-option label="同一天（间隔30分钟）" :value="2"></el-option>
                            <el-option label="每天" :value="3"></el-option>
                            <el-option label="间隔1天" :value="4"></el-option>
                            <el-option label="间隔2天" :value="5"></el-option>
                            <el-option label="间隔3天" :value="6"></el-option>
                            <el-option label="间隔4天" :value="7"></el-option>
                            <el-option label="间隔5天" :value="8"></el-option>
                            <el-option label="间隔一周" :value="9"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>    
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="⑦上课日期" prop="startDate">
                        <el-date-picker
                            clearable
                            v-model="form.startDate"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="选择日期"
                            :disabled-date="disabledDate"
                            @change="selectDateFun"
                        >
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="⑧上课时间" prop="startTime">
                        <el-time-select
                        v-model="form.startTime"
                        :start="startTime"
                        step="00:30"
                        :end="endTime"
                        placeholder="选择时间"
                        @change="selectTimeFun"
                        >
                        </el-time-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="⑨教练姓名" prop="teacherId">
                        <el-select v-model="form.teacherId" placeholder="请选择" clearable filterable style="width: 100%;">
                            <el-option :label="item.name" :value="item.id" v-for="item in teacherList"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            
        </el-form>
        <template #footer>
            <el-button @click="visible = false">取 消</el-button>
            <el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit()">{{ form.id ? '保 存' : '立即创建' }}</el-button>
            <el-button @click="emptyFun()">清 空</el-button>
        </template>
    </el-dialog>

    <courseSelectDom 
		ref="courseSelectDom" 
		@submit="submitAddCourse" 
		v-if="dialog.course" 
		@close="dialog.course = false"
        :userId="form.userId"
		:treeSearch="{type: '2'}"
		:defaultSearch="{containLearnNum: 1, courseStatus: '1', status: '1', userId: form.userId}"
	></courseSelectDom>
</template>

<script>
import courseSelectDom from './components/courseSelectDom.vue'
export default {
    emits: ['success', 'closed'],
    components: {
		courseSelectDom
	},
    props: {
        agentName: {
            type: String,
            default: ''
        },
        categoryData: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        return {
            mode: "add",
            titleMap: {
                add: '创建预约(时间优先)',
                edit: '编辑预约',
                show: '查看'
            },
            dialog: {
                course: false,
			},
            agentName: "",
            loading: false,
            visible: false,
            userLoading: false,
            isSaveing: false,
            //表单数据
            form: this.getDefaultRuleForm(),
            //验证规则
            rules: {
                courseType: [
                    { required: true, message: '请选择课程类型', trigger: 'change' },
                ],
                listenType: [
                    { required: true, message: '请选择交付方式', trigger: 'change' },
                ],
                userId: [
                    { required: true, message: '请选择学员', trigger: 'change' },
                ],
                courseId: [
                    { required: true, message: '请选择课程', trigger: 'change' },
                ],
                number: [
                    { required: false, message: '请选择预约次数', trigger: 'change' },
                ],
                startDate: [
                    { required: true, message: '请选择上课日期', trigger: 'change' },
                ],
                startTime: [
                    { required: true, message: '请选择上课时间', trigger: 'change' },
                ],
                teacherId: [
                    { required: true, message: '请选择教练', trigger: 'change' },
                ],
            },
            userList: [],
            userCourses: [],
            appointmentNumbers: 0, //可预约次数
            teacherList: [],
            startTime: '',
            endTime: '',
            selectedCourses: []
        }
    },
    created() {
        var userInfo = this.$TOOL.data.get("G_USER_INFO");
        this.agentName = userInfo.name;
    },
    mounted() {
    },
    methods: {
        //显示
        open(mode = 'add') {
            this.mode = mode;
            this.visible = true;
            return this
        },
        //选择课程弹窗
        addCourseFun(){
            if (!this.form.userId) {
                this.$notify.error('请先选择学员')
                return false
            }
            this.dialog.course = true
            this.$nextTick(() => {
                let arr = JSON.parse(JSON.stringify(this.selectedCourses))
                this.$refs.courseSelectDom.open(arr || [])
            })
		}, 
        async submitAddCourse(data) {
            let ids = data.map(item => { return item.course.id })
            this.dialog.course = false
            this.form.courseId = ids[0]
            this.selectedCourses = data
        },
        selectCourseTypeFun(row) {
            if (!this.form.id) {
                this.form.userId = ''
            }
            this.form.number = ''
            this.form.courseId = ''
            this.appointmentNumbers = 0
            this.searchUserHander()
        },
        selectUserFun(row) {
            if (this.form.courseType == 4) {
                this.getCourseCategory()
            }
            this.userList.forEach(ele => {
                if (ele.id == row) {
                    if (this.form.courseType == 1) {
                        this.appointmentNumbers = ele.classHour30
                    }else if (this.form.courseType == 2) {
                        this.appointmentNumbers = ele.classHour60
                    }else if (this.form.courseType == 3) {
                        this.appointmentNumbers = ele.classHour120
                    }else {
                        this.appointmentNumbers = 1
                    }
                }
                
            })
        },
        selectDateFun(row) {
            if (this.form.startDate) {
                this.getTeacherListHander()
            }
            let today = new Date()
            let month = today.getMonth() + 1
            if (month < 10) {
                month = '0' + month
            }
            let date = today.getDate()
            if (date < 10) {
                date = '0' + date
            }
            let todayStr = today.getFullYear() + '-' + month + '-' + date
            if (this.form.startDate == todayStr) {
                //判断当前时间是否超过半小时
                let nowTime = today.getMinutes()
                let hours = today.getHours() 
                if (hours < 23) {
                    if (nowTime > 30) {
                        hours = hours + 1
                        if (hours < 10) {
                            hours = '0' + hours
                        }
                        this.startTime = hours + ':00'
                        this.endTime = '23:00'
                    }else{
                        if (hours < 10) {
                            hours = '0' + hours
                        }
                        this.startTime = hours + ':30'
                        this.endTime = '23:00'
                    }
                }
            }else{
                this.startTime = '00:00'
                this.endTime = '23:00'
            }
        },
        selectTimeFun(row) {
            if (this.form.startDate) {
                this.getTeacherListHander()
            }
        },
        //表单提交方法
        submit() {
            this.$refs.dialogForm.validate(async (valid) => {
                if (!valid) {
                    return false
                }

                let data = {}
                for (let key in this.form) {
                    if (key == 'startData' || key == 'startTime') {
                        continue
                    }
                    data[key] = this.form[key]
                }

                if (this.form.courseType == 4) {
                    data.courseId = 0
                    data.courseCategoryId = this.form.courseId
                }

                data.startTime = this.form.startDate + ' ' + this.form.startTime

                try {
                    this.isSaveing = true;
                    if (this.form.id) {
                        await this.$API.appointment.action.put(data)
                    } else {
                        await this.$API.appointment.action.post(data)
                    }
                    this.$emit('success', this.form, this.mode)
                    this.visible = false;
                    this.$notify.success("保存成功")
                } finally {
                    this.isSaveing = false;
                }
            })
        },
        //表单注入数据
        async setData(row) {
            this.loading = true
            await this.$API.appointment.action.get({id: row.id}).then(res => {
                let _data = res.data
                let _form = {
                    id: _data.id,
                    userId: _data.user ? _data.user.id : '',
                    teacherId: _data.teacher ? _data.teacher.id : '',
                    courseId: _data.course ? _data.course.id  : '',
                    courseType: _data.courseType ? _data.courseType.value : '',
                    listenType: _data.listenType ? _data.listenType.value : '',
                    startDate: _data.date,
                    startTime: _data.startTime
                }

                if (_data.courseType.value == 4) {
                    _form.courseId = _data.courseCategory ? _data.courseCategory.id  : ''
                    this.getCourseCategory()
                }else {
                    let selectedCourses = []
                    selectedCourses.push({
                        course: _data.course
                    })
                    this.selectedCourses = selectedCourses
                }

                this.form = _form

                this.selectDateFun()
                this.searchUserHander()
                this.getUserCourseHander()
                this.getTeacherListHander()

            }).finally(() => {
				this.loading = false
			})
        },
        getDefaultRuleForm() {
            return {
                id: null,
                userId: '',
                teacherId: '',
                courseId: '',
                courseType: '',
                listenType: '',
                startDate: '',
                startTime: ''
            }
        },
        getUserCourseHander() {
            if (!this.form.userId) {
                return false
            }
            this.$API.user.course.all.get({
                userId: this.form.userId,
                status: 1,
                courseStatus: 1
            }).then((res) => {
                this.userCourses = res.data
            })
        },
        getCourseCategory() {
            this.$API.course.category.all.get({
            }).then((res) => {
                this.userCourses = res.data
            })
        },
        searchUserHander(query) {
            if (!this.form.courseType) {
                return false
            }
            this.userLoading = true;
            let params = {
                name:query, 
                courseType: this.form.courseType
            }
            if (this.form.courseType == 4) {
                params.courseType = 0
            }
            this.$API.user.listByName.get(params).then((res) => {
                let _data = []
                res.data.forEach(ele => {
                    if (this.form.courseType == 1) {
                        ele.disabled = ele.classHour30 == 0 ? true : false
                    }else if (this.form.courseType == 2) {
                        ele.disabled = ele.classHour60 == 0 ? true : false
                    }else if (this.form.courseType == 3) {
                        ele.disabled = ele.classHour120 == 0 ? true : false
                    }else {
                        ele.disabled = false
                    }
                    _data.push(ele)
                })
                this.userList = _data
            }).finally(() => {
                this.userLoading = false
            });
        },
        getTeacherListHander() {
            let startTime = ''
            if (this.form.startDate && this.form.startTime) {
                startTime = this.form.startDate + ' ' + this.form.startTime
            }else if (this.form.startDate) {
                startTime = this.form.startDate
            }
            this.$API.teacher.appointmentList.get({
                startTime: startTime,
                userId: this.form.userId,
            }).then((res) => {
                this.teacherList = res.data
            })
        },
        // 清空
        emptyFun() {
            let id = this.form.id ? this.form.id : null
            if (id) {
                this.form.courseType = ''
                this.form.listenType = ''
                this.form.courseId = ''
                this.form.startDate = ''
                this.form.startTime = ''
                this.form.teacherId = ''
                this.selectedCourses = []
            }else{
                this.form = this.getDefaultRuleForm()
                this.selectedCourses = []
            }
        },
        //禁用今天之前的日期
        disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
        }
    }
}
</script>

<style scoped>

.tipsbox {
    position: relative;
    left: 16px;
    bottom: 10px;
}

.tips-title {
    color: red; 
    margin-left: 20px; 
    margin-bottom: 10px; 
    font-size: 18px; 
    font-weight: bold;
}

.tips-con {
    color: red; 
    margin-left: 20px; 
    margin-bottom: 10px; 
    font-size: 14px; 
    font-weight: bold;
}

</style>
